package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.admin.utils.AdminUserThreadLocalUtils;
import com.zhentao.exception.CustomException;
import com.zhentao.exception.ExceptionCatch;
import com.zhentao.model.admin.rbac.SysPermission;
import com.zhentao.model.admin.rbac.SysUser;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.service.SysPermissionService;
import com.zhentao.mapper.SysPermissionMapper;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.zhentao.common.admin.rbac.SysAdminCommon.SYS_PERMISSION_SELECT_CACHE_KEY;
import static com.zhentao.common.admin.rbac.SysAdminCommon.SYS_USER_LOGIN_CACHE_EXPIRE_TIME;

/**
 * @author lenovo
 * @description 针对表【sys_permission(系统权限)】的数据库操作Service实现
 * @createDate 2024-12-26 19:14:23
 */
@Service
@Slf4j
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission>
        implements SysPermissionService {

    @Resource
    private SysPermissionMapper permissionMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * @param
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description 动态查询菜单
     * @author 振涛教育_小Q
     * @date 2024/12/26 21:08
     */
    @Override
    public ResponseResult menuList() {
        SysUser user = AdminUserThreadLocalUtils.getSysUser();
        if (StringUtils.checkValNull(user)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CHARGE_USER_DATA_NOT_EXIST);
        }
        String key = SYS_PERMISSION_SELECT_CACHE_KEY+user.getId();
        // 每次查询首先从缓存中查询，查询缓存中是否存在
        List<SysPermission> permissions;
        try {
            String permissionJSON = redisTemplate.opsForValue().get(key);
            if(!com.alibaba.cloud.commons.lang.StringUtils.isBlank(permissionJSON)){
                List<SysPermission> permissionCache = JSON.parseArray(permissionJSON, SysPermission.class);
                log.info("缓存中存在该用户的菜单信息");
                return ResponseResult.okResult(permissionCache);
            }
            // 查询菜单
            permissions = permissionMapper.selectMenuByUserIds(user.getId());
            if(permissions != null && permissions.size() > 0){
                for (SysPermission permission : permissions) {
                    List<SysPermission> permissionsList = permissionMapper.getAllByPerId(permission.getId());
                    permission.setChildren(permissionsList);
                }
            }
            Iterator<SysPermission> iterator = permissions.iterator();
            while (iterator.hasNext()) {
                SysPermission permission = iterator.next();
                if(Long.parseLong(permission.getPid()) != 0L){
                    iterator.remove();
                }
            }
        } catch (Exception e) {
            throw new CustomException(AppHttpCodeEnum.NULL_EXCEPTION);
        }
        // 存放在缓存当中
        redisTemplate.opsForValue().set(key, JSON.toJSONString(permissions));
        // 设置过期时间
        redisTemplate.expire(key, SYS_USER_LOGIN_CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
        log.info("已经成功将 permission 存放在缓存当中");
        return ResponseResult.okResult(permissions);
    }

}




